from django.http import HttpResponse, JsonResponse
import json
from dvadmin.lowcode import models

from dvadmin.system.models import Menu

def model2jsonArr(data):
    rData = []
    for p in data:
        p.__dict__.pop("_state")  # 除去'model、pk'
        rData.append(p.__dict__)
    return rData




def LowDataTypedView(request):
    ret = {"status": True, "code": 2000, "msg": "", "data": []}
    # obj = models.LowDataTyped.objects.a`ll()

    # Create your views here.
    # 从数据库获取菜单树
    def get_menu_tree():
        tree = []
        menus = models.LowDataTyped.objects.filter(pid=None)
        for menu in menus:
            menu_data = {
                "key": menu.id,
                "label": menu.name,
                "value": menu.id,

                "children": []
            }
            childs = models.LowDataTyped.objects.filter(pid=menu)
            if childs:
                menu_data["children"] = get_child_menu(childs)
            tree.append(menu_data)
        return tree

    # 递归获取所有的子菜单
    def get_child_menu(childs):
        children = []
        if childs:
            for child in childs:
                data = {
                    "key": child.id,
                    "value":child.id,
                    "label": child.name,
                    "children": []
                }
                _childs = models.LowDataTyped.objects.filter(pid=child)
                if _childs:
                    data["children"].append(get_child_menu(_childs))
                children.append(data)
        return children
    ret['data']=get_menu_tree()

    return JsonResponse(ret)

def BlockView(request):
    ret = {"status": True,"code":2000, "msg": "", "data": []}

    if request.method == "POST":
        json_str = request.body
        json_dict = json.loads(json_str)
        data = json_dict.get("block", None)
        obj = models.Block(schema=data['schema'], screenshot=data['screenshot'], title=data['title'], blockTypeId_id=data['typed'])
        # obj.name = data['name']
        # obj.schema = data['schema']
        # obj.screenshot = data['screenshot']
        # obj.title = data['title']

        obj.save()
        # obj.name = json_dict.get("key", None)
        # page = request.GET["block"]
        # print(page)

        return HttpResponse(json.dumps(ret))
    if request.method == "GET":
        typed = request.GET['typed']
        search = request.GET['search']
        if typed == 'undefined':
            typed = None
        if search == "undefined":
            search = None
        obj = models.Block.objects.filter()


        ret['data'] = model2jsonArr(obj)
        return HttpResponse(json.dumps(ret))

    if request.method == "GET":
        print("get")
        ret = {"status": True,"code":2000, "msg": "", "data": []}
        return HttpResponse(json.dumps(ret))


